public class ReverseKGroup {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummyHead = new ListNode();
        int count = 0;
        ListNode temp = head;
        ListNode temp2 = dummyHead;
        ListNode tempHead = new ListNode();
        ListNode end = dummyHead;
        while (temp != null) {
            if (count == k) {
                temp2.next = tempHead.next;
                temp2 = end;
                tempHead = new ListNode();
                count = 0;
            }
            if (count == 0) {
                end = temp;
            }
            ListNode next = temp.next;
            temp.next = tempHead.next;
            tempHead.next = temp;
            temp = next;
            count++;
        }
        if (count == k) {
            temp2.next = tempHead.next;
        } else {
            tempHead = tempHead.next;
            while (tempHead != null) {
                ListNode next = tempHead.next;
                tempHead.next = temp2.next;
                temp2.next = tempHead;
                tempHead = next;
            }
        }
        return dummyHead.next;
    }
}
